package com.cdu.guoxinan.www.smartcom.util;

import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        
        System.out.println("=== JWT过滤器开始执行 ===");
        System.out.println("请求URL: " + request.getRequestURI());
        System.out.println("请求方法: " + request.getMethod());
        
        String token = request.getHeader("Authorization");
        System.out.println("Authorization头: " + token);
        
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            System.out.println("提取的token: " + token);
            
            if (JwtUtil.validateToken(token)) {
                System.out.println("Token验证成功");
                String username = JwtUtil.getUsername(token);
                System.out.println("用户名: " + username);
                
                // 这里获取claims
                Claims claims = JwtUtil.getClaims(token);
                // ====== 你要加的代码 START ======
                String role = claims.get("role", String.class);
                //控制台输出
                System.out.println("从token中获取的role: " + role);
                
                // 确保角色名称正确（如果数据库返回的已经是ROLE_开头，就不需要再添加）
                String authorityRole = role;
                if (!role.startsWith("ROLE_")) {
                    authorityRole = "ROLE_" + role;
                }
                System.out.println("最终使用的角色: " + authorityRole);
                
                List<GrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority(authorityRole));
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(username, null, authorities);
                // ====== 你要加的代码 END ======
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
                System.out.println("认证信息已设置到SecurityContext");
            } else {
                System.out.println("Token验证失败");
            }
        } else {
            System.out.println("没有找到有效的Authorization头");
        }
        
        System.out.println("=== JWT过滤器执行完成 ===");
        chain.doFilter(request, response);
    }
}